package com.imooc.controller;

import com.imooc.vo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 *
 */
@RestController
public class UserController {

    @RequestMapping(value = "/subLogin",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    public String subLogin( User user){
        //获取Shiro主体
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return e.getMessage();
        }

        if (subject.isPermitted("user:add") && subject.hasRole("admin")){
            return "欢迎admin莅临***";
        }
        return "登录成功";
    }
/*#####################################   测试注解做授权访问控制   ############################*/
    @RequiresRoles("admin")//当前的主体（Subject）必须具备Admin角色才能访问
    @RequestMapping(value = "/testRole",method = RequestMethod.GET)
    public String testRole(){
        return "testRole success";
    }

    @RequiresRoles("admin1")//当前的主体（Subject）必须具备Admin角色才能访问
    @RequestMapping(value = "/testRole1",method = RequestMethod.GET)
    public String testRole1(){
        return "testRole success";
    }
/*#####################################   测试   ############################*/
    @RequestMapping(value = "/testPerms",method = RequestMethod.GET)
    public String testPerms(){
        return "testPerms success";
    }
    @RequestMapping(value = "/testPerms1",method = RequestMethod.GET)
    public String testPerms1(){
        return "testPerms1 success";
    }

/*######################################  自定义filter  ############################*/

@RequestMapping(value = "/testRole2",method = RequestMethod.GET)
public String testRole2(){
    return "testRole success";
}
}
